package com.example.myapplication;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.LinearLayout;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/6/23.
 */

public class PhotoPickerActivity extends Activity implements View.OnClickListener,AdapterView.OnItemClickListener{
    private GridAdapter mGridAdapter;
    private GridView gv_photoPicker_content;
    private Button btn_photoPicker_take;
    private Button btn_photoPicker_delete;
    private Button btn_photoPicker_return;


    private String pictures="";
    private ArrayList<PhotoInfo> photoList=new ArrayList<>();
    private ArrayList<PhotoInfo> selectedList=new ArrayList<>();
    private static final int CODE = 1;


    private String strImgPath;
    private String fileName;
    private Uri uri;


    private String point;
    private String address;
    private String thirdIndex;
    private String standard;
    private String code;
    private String areaCode;
    private int position;

    private SharedPreferences sharedPreferences;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photopicker);
        initView();
        getPhotos();
    }

    private void initView() {
        btn_photoPicker_delete=(Button)findViewById(R.id.btn_photoPicker_delete);
        btn_photoPicker_take=(Button)findViewById(R.id.btn_photoPicker_take);
        btn_photoPicker_return=(Button)findViewById(R.id.btn_photoPicker_return);
        gv_photoPicker_content=(GridView)findViewById(R.id.gv_photoPicker_content);
        mGridAdapter=new GridAdapter(photoList,PhotoPickerActivity.this);
        gv_photoPicker_content.setAdapter(mGridAdapter);
        mGridAdapter.notifyDataSetChanged();

        btn_photoPicker_take.setOnClickListener(this);
        btn_photoPicker_delete.setOnClickListener(this);
        btn_photoPicker_return.setOnClickListener(this);
        gv_photoPicker_content.setOnItemClickListener(this);

        //获取intent传递数据
        Bundle bundle=getIntent().getExtras();
        point=bundle.getString("point");
        address=bundle.getString("address");
        thirdIndex=bundle.getString("thirdIndex");
        standard=bundle.getString("standard");
        code=bundle.getString("code");
        position=bundle.getInt("position");


        //获取sharePreferences中的地区编码
        sharedPreferences=getSharedPreferences("myData",MODE_PRIVATE);
        areaCode=sharedPreferences.getString("excelName","");
        Log.d("myExcelName",areaCode);

        //获取数据库中所有图片
        Log.d("myPointandAddress",String.valueOf(point)+String.valueOf(address)+String.valueOf(standard)+String.valueOf(code)+String.valueOf(thirdIndex));
        List<Investigation> investigations= DataSupport.select("picture")
                .where("point = ? and address = ? and standard = ? and code = ? and thirdIndex = ?",point,address,standard,code,thirdIndex)
                .find(Investigation.class);

        String.valueOf(investigations.get(0).getPicture());
        pictures=investigations.get(0).getPicture();
        Log.d("myGetPictureGG",pictures);

     /*   //清空数据库中的图片
        Investigation investigation=new Investigation();
        Log.d("myPictures",pictures);
        investigation.setPicture("");
        investigation.updateAll("point = ? and address = ? and standard = ? and code = ? and thirdIndex = ?",point,address,standard,code,thirdIndex);*/

    }

    //得到照片
    private void getPhotos(){
        if(pictures!=null && pictures !="") {
            String myString=new String(pictures);
            Log.d("mymString",myString);
            int start=0;
            //获取图片名串中的每张图片名
            while(start!=pictures.length()){
                myString=myString.substring(start);
                Log.d("mymmString",myString);
                Log.d("myStart",String.valueOf(start));
                PhotoInfo photoInfo = new PhotoInfo();
                photoInfo.setChecked(false);
                String photoName="";
                Log.d("myString,",String.valueOf(myString.indexOf("/r/n")));
                if(myString.indexOf("/r/n")<0)break;
                photoName=myString.substring(0,myString.indexOf("/r/n"));
                Log.d("myPhotoName",photoName);
                photoInfo.setUrl(Environment.getExternalStorageDirectory()
                        .toString() + "/"+areaCode+"/"+photoName);
                mGridAdapter.getList().add(photoInfo);
                start=myString.indexOf("/r/n")+4;
            }
            mGridAdapter.notifyDataSetChanged();
        }

    }

    //拍照
    private void takePhoto(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //指定拍照
         strImgPath = Environment.getExternalStorageDirectory()
                .toString() + "/"+areaCode+"/";
        Log.d("myAreaCode",areaCode);
         fileName = areaCode+"_"+point+"_"+thirdIndex+"-"+standard+"-"+code+new SimpleDateFormat("yyyyMMddHHmmss")
                .format(new Date())+"_big" + ".jpg";// 照片以格式化日期方式命名
        String imageName=strImgPath+fileName;
        Log.d("myImageName",imageName);
        File out = new File(strImgPath);
        if (!out.exists()) {
            out.mkdirs();
        }

        out = new File(strImgPath, fileName);
        String mStrImgPath = strImgPath + fileName;// 该照片的绝对路径
        uri = Uri.fromFile(out);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//根据uri保存照片
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);//保存照片的质量
        startActivityForResult(intent, CODE);
    }

    //删除图片
    private void deletePhoto(){
        selectedList.clear();
        for(int i=0;i<mGridAdapter.getList().size();i++){
            Log.d("myChecked",String.valueOf(mGridAdapter.getList().get(i).isChecked()));
            if(mGridAdapter.getList().get(i).isChecked()==true)
                selectedList.add(mGridAdapter.getList().get(i));
        }
        //删除选中的图片
        Log.d("mySize",String.valueOf(selectedList.size()));
        for(int i=0;i<selectedList.size();i++){
                PhotoInfo photoInfo=selectedList.get(i);
                File file = new File(photoInfo.getUrl());
                file.delete();
                Log.d("myPhotoPath",photoInfo.getUrl());
               //删除pictures中的图片
                pictures=pictures.replace(photoInfo.getUrl().replace(Environment.getExternalStorageDirectory()
                        .toString() + "/"+areaCode+"/","")+"/r/n","");
            Log.d("myDelete",photoInfo.getUrl()+",");
            Log.d("myGetPictureg",pictures+"Aaa");

            //图片checkBox点击状态的设置
            FrameLayout layout = (FrameLayout) gv_photoPicker_content.getChildAt(mGridAdapter.getList().indexOf(selectedList.get(i)));// 获得子item的layout
            CheckBox checkBox=(CheckBox) layout.findViewById(R.id.cb_image_selected);
            checkBox.setChecked(false);
            mGridAdapter.getList().remove(selectedList.get(i));
        }
        //更新数据库中的图片
        Investigation investigation=new Investigation();
        Log.d("mygPictures",pictures);
        investigation.setPicture(pictures);
        investigation.updateAll("point = ? and address = ? and standard = ? and code = ? and thirdIndex = ?",point,address,standard,code,thirdIndex);
        mGridAdapter.notifyDataSetChanged();
    }

   /* private void savePhoto(){
     *//*   Investigation investigation=new Investigation();
        Log.d("myPictures",pictures);
        investigation.setPicture(pictures);
        investigation.updateAll("point = ? and address = ?",point,address);*//*
        finish();
    }*/

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 判断是否返回值
        if (resultCode == RESULT_OK) {
            // 判断返回值是否正确
            if (requestCode == CODE) {
               /* File imageFile = new File(strImgPath);*/
               /* // 获取图片
                Bundle bundle = data.getExtras();
                // 转换图片的二进制流
                Bitmap bitmap = (Bitmap) bundle.get("data");*/
                // 设置图片
                PhotoInfo photoInfo=new PhotoInfo();
                photoInfo.setUrl(strImgPath+fileName);
                pictures=pictures+fileName+"/r/n";
                Log.d("myPicture",pictures);
                photoInfo.setChecked(false);
                Log.d("myPath",strImgPath+fileName);
                mGridAdapter.getList().add(photoInfo);

                //更新数据库中的图片
                Investigation investigation=new Investigation();
                Log.d("myPictures",pictures);
                investigation.setPicture(pictures);
                investigation.updateAll("point = ? and address = ? and standard = ? and code = ? and thirdIndex = ?",point,address,standard,code,thirdIndex);
                mGridAdapter.notifyDataSetChanged();
            }
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_photoPicker_take:
                takePhoto();
                break;
            case R.id.btn_photoPicker_delete:
                deletePhoto();
                break;
            case R.id.btn_photoPicker_return:
                Intent intent=new Intent();
                PhotoPickerActivity.this.setResult(0,intent);
                finish();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        Intent intent=new Intent();
      /*  Log.d("myNum",String.valueOf(getPictureNum()));
        intent.putExtra("num",getPictureNum());
        intent.putExtra("position",position);*/
        this.setResult(0,intent);
        finish();
    }



    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
       /* Log.d("myPosition",String.valueOf(i)+"aaa");
        LinearLayout layout = (LinearLayout) gv_photoPicker_content.getChildAt(i);// 获得子item的layout
        CheckBox checkBox=(CheckBox) layout.findViewById(R.id.cb_image_selected);
        checkBox.setChecked(true);
        *//*checkBox.setChecked(!checkBox.isChecked());*//*
        mGridAdapter.getList().get(i).setChecked(!checkBox.isChecked());*/
    }
}
